package com.eightbears.beboy.ui.user.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.entity.CouponsEntity;
import com.eightbears.beboy.entity.OrderDetailEntity;
import com.eightbears.beboy.entity.OrderEntity;
import com.eightbears.beboy.entity.PayOrderEntity;
import com.eightbears.beboy.entity.WaitPaymentEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT_VALUE;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_ALREADY_COMMENT;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_APPLY_REFOUND;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_BUY;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_CANCEL;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_END_DATE;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_ORDER_WAIT_PAY;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_REFOUND_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_UNUSE;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_USE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_GETSHOPMAELRCODE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_ORDER_DETAIL;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAYMENT_ORDERS;
import static com.eightbears.beboy.entity.WaitPaymentEntity.PARAMS_WAIT_PAYMENT;
import static com.eightbears.beboy.ui.user.activity.RefundActivity.EVENT_REFUND;
import static com.eightbears.beboy.ui.user.fragment.WaitUseOrderFragment.PARAMS_ORDER_LIST;

public class OrderDetailActivity extends BaseActivity {

    public static final String PARAMS_ORDER_DETAIL = "orderDetail";
    public static final String PARAMS_ORDER_INFO = "orderInfo";
    public static final String PARAMS_BUY_SETWEAL = "buySetWeal";
    public static final String PARAMS_PAY_ORDER = "payOrder";
    public static final String EVENT_CANCEL_ORDER = "cancelOrder";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.rv_list)
    ListView rv_list;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_goods)
    TextView tv_goods;
    @BindView(R.id.iv_goods_cover)
    ImageView iv_goods_cover;
    @BindView(R.id.tv_discount_price)
    TextView tv_discount_price;
    @BindView(R.id.tv_cost_price)
    TextView tv_cost_price;
    @BindView(R.id.tv_count)
    TextView tv_count;
    @BindView(R.id.tv_date)
    TextView tv_date;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_status)
    TextView tv_status;
    @BindView(R.id.tv_event_btn)
    TextView tv_event_btn;
    @BindView(R.id.ll_refund)
    LinearLayout ll_refund;
    @BindView(R.id.tv_total_amount)
    TextView tv_total_amount;
    @BindView(R.id.tv_red_package)
    TextView tv_red_package;
    @BindView(R.id.tv_receipt_amount)
    TextView tv_receipt_amount;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_order_info)
    TextView tv_order_info;
    @BindView(R.id.rl_manager)
    RelativeLayout rl_manager;
    @BindView(R.id.ll_title)
    LinearLayout ll_title;
    @BindView(R.id.view_bottom_list)
    LinearLayout view_bottom_list;

    private DefaultDialog.Builder builder;

    private String phone;
    private CouponsEntity.Coupons coupons;
    private OrderDetailEntity orderDetailEntity;
    private OrderEntity.OrderInfo orderInfo;
    private WaitPaymentEntity.WaitPayment waitPayment;

    private PayOrderEntity.PayOrder payOrder;
    private OrderEntity.OrderDetailEntity orderDetail;
    private String orderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        coupons = (CouponsEntity.Coupons) getIntent().getExtras().get(PARAMS_ORDER_DETAIL);
        waitPayment = (WaitPaymentEntity.WaitPayment) getIntent().getExtras().get(PARAMS_WAIT_PAYMENT);
        orderInfo = (OrderEntity.OrderInfo) getIntent().getExtras().get(PARAMS_ORDER_LIST);
        payOrder = (PayOrderEntity.PayOrder) getIntent().getExtras().get(PARAMS_PAY_ORDER);

        if (null != coupons) {
            orderId = coupons.getId();
            initBuySetMeal();
        }

        if (null != waitPayment) {
            orderId = waitPayment.getId();
            initWaitPayment();
        }

        if (null != orderInfo) {
            orderId = orderInfo.getOrder_id();
            initOrderList();
        }

        if (null != payOrder) {
            getOrderDetail();
        }
    }

    private void initBuySetMeal() {
        showBuySetMeal();
        String disPrice = String.format(getString(R.string.text_price), coupons.getDiscount_price());
        String price = String.format(getString(R.string.text_price), coupons.getPrice());
        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(coupons.getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(coupons.getEnd_at(), "yyyy-MM-dd"));
        phone = coupons.getManagers().getMobile();
        tv_title.setText(coupons.getTitle());
        tv_goods.setText(coupons.getContent());
        tv_discount_price.setText(disPrice);
        tv_cost_price.setText(price);
        tv_count.setText(coupons.getRec_num());
        tv_date.setText(date);
        tv_nickname.setText(coupons.getManagers().getName());
        CommonUtils.loadImageView(getApplication(), coupons.getCover(), R.mipmap.default_icon, iv_goods_cover);
        CommonUtils.loadImageView(getApplication(), coupons.getManagers().getCover(), R.mipmap.icon_default_shop, iv_head);
    }

    private void initWaitPayment() {
        showCancelOrder();
        String disPrice = String.format(getString(R.string.text_price), waitPayment.getObject().getDiscount_price());
        String price = String.format(getString(R.string.text_price), waitPayment.getObject().getPrice());
        String redPrice = String.format(getString(R.string.text_price), waitPayment.getHong_bao_amount());
        String totalPrice = String.format(getString(R.string.text_price), waitPayment.getTotal_amount());

        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(waitPayment.getObject().getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(waitPayment.getObject().getEnd_at(), "yyyy-MM-dd"));
        tv_title.setText(waitPayment.getObject().getTitle());
        tv_goods.setText(waitPayment.getObject().getContent());
        tv_discount_price.setText(disPrice);
        tv_cost_price.setText(price);
        tv_date.setText(date);
        tv_count.setText(waitPayment.getObject().getRec_num());
        tv_total_amount.setText(disPrice);
        tv_red_package.setText(redPrice);
        tv_receipt_amount.setText(totalPrice);
        CommonUtils.loadImageView(getApplication(), waitPayment.getObject().getCover(), R.mipmap.default_icon, iv_goods_cover);
    }

    private void initOrderList() {
        rl_manager.setVisibility(View.GONE);
        if (orderInfo.getStatus().equals(STATUS_UNUSE)) {
            showUnUseStatus();
        } else if (orderInfo.getStatus().equals(STATUS_USE)) {
            showEndDate();
        } else if (orderInfo.getStatus().equals(STATUS_END_DATE)) {
            showEndDate();
        } else if (orderInfo.getStatus().equals(STATUS_APPLY_REFOUND)) {
            showRefund();
        } else if (orderInfo.getStatus().equals(STATUS_REFOUND_SUCCESS)) {
            showRefundSuccess();
        } else if (orderInfo.getStatus().equals(STATUS_ALREADY_COMMENT)) {
            showEndDate();
        }

        String disPrice = String.format(getString(R.string.text_price), orderInfo.getCoupon().getDiscount_price());
        String price = String.format(getString(R.string.text_price), orderInfo.getCoupon().getPrice());
        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(orderInfo.getCoupon().getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(orderInfo.getCoupon().getEnd_at(), "yyyy-MM-dd"));
        tv_title.setText(orderInfo.getCoupon().getTitle());
        tv_goods.setText(orderInfo.getCoupon().getContent());
        tv_discount_price.setText(disPrice);
        tv_cost_price.setText(price);
        tv_date.setText(date);
        tv_count.setText(orderInfo.getCoupon().getRec_num());
        CommonUtils.loadImageView(getApplication(), orderInfo.getCoupon().getCover(), R.mipmap.default_icon, iv_goods_cover);

    }

    private void initOrderDetail() {
        orderId = orderDetail.getData().getOrder_id();
        rl_manager.setVisibility(View.GONE);

        String disPrice = String.format(getString(R.string.text_price), orderDetail.getData().getAmount());
        String price = String.format(getString(R.string.text_price), orderDetail.getData().getPrice());
        String date = String.format(getString(R.string.text_valid_date),
                CommonUtils.TimeStamp2Date(orderDetail.getData().getStart_at(), "yyyy-MM-dd"),
                CommonUtils.TimeStamp2Date(orderDetail.getData().getEnd_at(), "yyyy-MM-dd"));
        tv_title.setText(orderDetail.getData().getTitle());
        tv_goods.setText(orderDetail.getData().getContent());
        tv_discount_price.setText(disPrice);
        tv_cost_price.setText(price);
        tv_date.setText(date);
        tv_count.setText(orderDetail.getData().getRec_num());
        orderInfo = new OrderEntity.OrderInfo();
        OrderEntity.Order order = new OrderEntity.Order();
        order.setReceipt_amount(orderDetail.getData().getOrder().getReceipt_amount());
        order.setTotal_amount(orderDetail.getData().getOrder().getTotal_amount());
        orderInfo.setOrder(order);
        CommonUtils.loadImageView(getApplication(), orderDetail.getData().getCover(), R.mipmap.default_icon, iv_goods_cover);


        KLog.e(orderDetail.getData().getStatus());
        if(payOrder.getStatus().equals(STATUS_ORDER_WAIT_PAY)) {
            hiedView();
        } else {
            if (orderDetail.getData().getStatus().equals(STATUS_UNUSE)) {
                showUnUseStatus();
            } else if (orderDetail.getData().getStatus().equals(STATUS_USE)) {
                showEndDate();
            } else if (orderDetail.getData().getStatus().equals(STATUS_END_DATE)) {
                showEndDate();
            } else if (orderDetail.getData().getStatus().equals(STATUS_APPLY_REFOUND)) {
                showRefund();
            } else if (orderDetail.getData().getStatus().equals(STATUS_REFOUND_SUCCESS)) {
                showRefundSuccess();
            } else if (orderDetail.getData().getStatus().equals(STATUS_ALREADY_COMMENT)) {
                showEndDate();
            }

        }

    }

    private void getOrderDetail() {
        String url = URL_GETSHOPMAELRCODE + payOrder.getObject().getCode();
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addHeader(KEY_HTTP_HEADER_ACCEPT, KEY_HTTP_HEADER_ACCEPT_VALUE)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                orderDetail = GsonUtil.fromJson(response, OrderEntity.OrderDetailEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(orderDetail.getStatus_code())) {
                    initOrderDetail();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(OrderDetailActivity.this, status_error);
            }
        });
    }

    @Override
    protected void initData() {
        List<String> items = Arrays.asList(getResources().getStringArray(R.array.ScheduleInfo));
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item_alert, R.id.tv_item_name, items);
        rv_list.setAdapter(adapter);
        getOrder();
    }

    private void getOrder() {
        OkHttpUtils.get().url(URL_ORDER_DETAIL + orderId)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                orderDetailEntity = GsonUtil.fromJson(response, OrderDetailEntity.class);
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = new Status_Error();
                ErrorUtils.alertError(OrderDetailActivity.this, status_error);
            }

        });
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_phone)
    void callManager() {
        if (!TextUtils.isEmpty(phone)) {
            CommonUtils.call(OrderDetailActivity.this, phone);
        }
    }

    @OnClick(R.id.tv_event_btn)
    void subEvent() {
        switch (tv_event_btn.getTag().toString()) {
            case STATUS_BUY:
                startLocalActivity(this, PaymentActivity.class, PARAMS_BUY_SETWEAL, orderDetailEntity.getData());
                break;
            case STATUS_CANCEL:
                if (builder == null) {
                    builder = new DefaultDialog.Builder(this);
                    builder.setTitle(R.string.text_cancel_order);
                    builder.setMessage("是否取消订单?");
                    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            cancelOrder();
                            dialog.dismiss();
                        }
                    });
                }
                builder.create().show();
                break;
            case STATUS_UNUSE:
                if (null != orderInfo && orderInfo.getShop() != null)
                    startLocalActivity(this, RefundActivity.class, PARAMS_ORDER_INFO, orderInfo);
                if (null != orderDetail && orderDetail.getData() != null)
                    startLocalActivity(this, RefundActivity.class, PARAMS_PAY_ORDER, orderDetail);
                break;
            case STATUS_END_DATE:
                KLog.e(orderInfo);
                if (null != orderInfo && orderInfo.getShop() != null)
                    startLocalActivity(this, PaymentActivity.class, PARAMS_ORDER_INFO, orderInfo);
                if (null != orderDetail && orderDetail.getData() != null)
                    startLocalActivity(this, PaymentActivity.class, PARAMS_PAY_ORDER, orderDetail);
                break;
        }

    }

    private void cancelOrder() {
        OkHttpUtils.put().url(URL_PAYMENT_ORDERS + orderId)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("status", STATUS_CANCEL)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_order_cancel_success));
                EventBus.getDefault().post(EVENT_CANCEL_ORDER);
                finish();
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = new Status_Error();
                ErrorUtils.alertError(OrderDetailActivity.this, status_error);
            }
        });
    }

    private void showBuySetMeal() {
        view_bottom_list.setVisibility(View.VISIBLE);
        ll_refund.setVisibility(View.GONE);
        rv_list.setVisibility(View.VISIBLE);
        tv_event_btn.setText(getString(R.string.text_buy));
        tv_event_btn.setBackgroundResource(R.drawable.background_circle_bead_blue_style);
        tv_event_btn.setTextColor(getResources().getColor(R.color.text_color_fff));
        tv_event_btn.setVisibility(View.VISIBLE);
        tv_event_btn.setTag(STATUS_BUY);
    }
    private void hiedView() {
        ll_refund.setVisibility(View.GONE);
        view_bottom_list.setVisibility(View.GONE);
        tv_event_btn.setText(getString(R.string.text_buy));
        tv_event_btn.setBackgroundResource(R.drawable.background_circle_bead_blue_style);
        tv_event_btn.setTextColor(getResources().getColor(R.color.text_color_fff));
        tv_event_btn.setVisibility(View.GONE);
        tv_event_btn.setTag(STATUS_BUY);
    }

    private void showCancelOrder() {
        view_bottom_list.setVisibility(View.VISIBLE);
        rl_manager.setVisibility(View.GONE);
        ll_title.setVisibility(View.GONE);
        rv_list.setVisibility(View.GONE);
        ll_refund.setVisibility(View.VISIBLE);

        tv_event_btn.setText(R.string.text_cancel_order);
        tv_event_btn.setBackgroundResource(R.drawable.bg_gray_style);
        tv_event_btn.setTag(STATUS_CANCEL);

    }

    private void showUnUseStatus() {
        view_bottom_list.setVisibility(View.VISIBLE);
        ll_refund.setVisibility(View.VISIBLE);
        rv_list.setVisibility(View.GONE);
        tv_event_btn.setText("申请退款");
        tv_order_info.setText("订单详情");
        tv_event_btn.setBackgroundResource(R.drawable.bg_pay_red_style);
        tv_event_btn.setTag(STATUS_UNUSE);
        tv_event_btn.setVisibility(View.VISIBLE);
        showListInfo();
    }

    private void showUseStatus() {
        ll_refund.setVisibility(View.VISIBLE);
        rv_list.setVisibility(View.GONE);
        tv_event_btn.setText("评论");
        tv_order_info.setText("订单详情");
        tv_event_btn.setBackgroundResource(R.drawable.background_circle_bead_blue_style);
        tv_event_btn.setTag(STATUS_USE);
        tv_event_btn.setVisibility(View.VISIBLE);
        showListInfo();
    }

    private void showEndDate() {
        view_bottom_list.setVisibility(View.VISIBLE);
        tv_event_btn.setText("再次购买");
        tv_event_btn.setBackgroundResource(R.drawable.bg_pay_red_style);
        tv_event_btn.setTag(STATUS_END_DATE);
        tv_event_btn.setVisibility(View.VISIBLE);
        showListInfo();
    }

    private void showRefund() {
        view_bottom_list.setVisibility(View.VISIBLE);
        ll_refund.setVisibility(View.VISIBLE);
        rv_list.setVisibility(View.GONE);
        tv_event_btn.setText("退款中");
        tv_order_info.setText("订单详情");
        tv_event_btn.setBackgroundResource(R.color.transparent_00000);
        tv_event_btn.setTextColor(getResources().getColor(R.color.text_other_info_color));
        tv_event_btn.setTag(STATUS_APPLY_REFOUND);
        tv_event_btn.setVisibility(View.VISIBLE);
        showListInfo();
    }

    private void showRefundSuccess() {
        view_bottom_list.setVisibility(View.VISIBLE);
        ll_refund.setVisibility(View.VISIBLE);
        rv_list.setVisibility(View.GONE);
        tv_event_btn.setText("已退款");
        tv_event_btn.setBackgroundResource(R.color.transparent_00000);
        tv_event_btn.setTextColor(getResources().getColor(R.color.text_other_info_color));
        tv_event_btn.setTag(STATUS_REFOUND_SUCCESS);
        tv_order_info.setText("订单详情");
        showListInfo();
    }


    private void showAlreadyComment() {
        ll_refund.setVisibility(View.VISIBLE);
        rv_list.setVisibility(View.GONE);
        tv_event_btn.setText("已评论");
        tv_event_btn.setBackgroundResource(R.color.transparent_00000);
        tv_event_btn.setTextColor(getResources().getColor(R.color.text_other_info_color));
        tv_order_info.setText("订单详情");
        showListInfo();
    }

    private void showListInfo() {
        ll_refund.setVisibility(View.VISIBLE);
        rv_list.setVisibility(View.GONE);
        double total = Double.parseDouble(orderInfo.getOrder().getTotal_amount());
        double receipt = Double.parseDouble(orderInfo.getOrder().getReceipt_amount());
        double redPackage = total - receipt;
        String totalPri = String.format(getString(R.string.text_price), String.valueOf(total));
        String receiptPri = String.format(getString(R.string.text_price), String.valueOf(receipt));
        String redPackagePri = " - " + String.format(getString(R.string.text_price), String.valueOf(redPackage));

        tv_total_amount.setText(totalPri);
        tv_receipt_amount.setText(receiptPri);
        tv_red_package.setText(redPackagePri);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_REFUND:
                showRefund();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
